<template>
  <div class="flex items-center justify-center h-screen bg-gray-200">
    <div class="w-full max-w-sm p-6 bg-white rounded-lg shadow-md">
      <div class="mb-8 text-center">
        <h1 class="text-3xl font-bold text-gray-700">PUMS</h1>
      </div>

      <div class="mb-4">
        <label for="email" class="block mb-2 font-semibold text-gray-700">用户名</label>
        <input id="email" type="text" v-model="loginData.userName"
          class="w-full px-4 py-2 text-gray-700 bg-gray-100 border rounded-lg focus:outline-none focus:border-blue-500 focus:bg-white" />
      </div>

      <div class="mb-6">
        <label for="password" class="block mb-2 font-semibold text-gray-700">密码</label>
        <input id="password" type="password" v-model="loginData.userPwd"
          class="w-full px-4 py-2 text-gray-700 bg-gray-100 border rounded-lg focus:outline-none focus:border-blue-500 focus:bg-white" />
      </div>

      <div class="mb-4 flex items-center justify-between">
        <img alt="验证码" :src="codeBase64" class="w-[100px] h-[50px] cursor-pointer" @click="createImgCodeClick" />
        <div class="relative">
          <input id="captcha" type="text" v-model="loginData.verificationCode" @keyup.enter="login"
            class="w-32 px-4 py-2 text-gray-700 bg-gray-100 border rounded-lg focus:outline-none focus:border-blue-500 focus:bg-white" />
        </div>
      </div>
      <div class="mb-6">
        <button @click="login"
          class="w-full px-4 py-2 text-white bg-blue-500 rounded-lg hover:bg-blue-600 focus:outline-none focus:bg-blue-600">
          登录
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { createImageCode, userLogin } from '@/api/user/user'
import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import Fingerprint2 from 'fingerprintjs2'

const userStore = useUserStore()

const loginData = reactive({
  userName: '',
  userPwd: '',
  murmur: '', // 浏览器指纹
  verificationCode: ''  // 验证码
})

const codeBase64 = ref('')


const createImgCodeClick = () => {
  createImageCode({ murmur: loginData.murmur }).then(res => {
    codeBase64.value = res.data.image
  })
}

const login = () => {
  userLogin(loginData).then(res => {
    if (res.code !== 200) {
      loginData.verificationCode = ''
      codeBase64.value = res.data.image
    } else if (res.code == 200 && res.data.token) {
      userStore.setToken(res.data.token)
      userStore.setUserData(res.data)

      router.push('/')
    }

  })
}

onMounted(async () => {
  const components = await Fingerprint2.getPromise()
  const values = components.map(component => component.value)
  loginData.murmur = Fingerprint2.x64hash128(values.join(''), 31)

  createImgCodeClick()
})
</script>

<style lang="scss" scoped></style>